﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Linq.Expressions;
using System.Data.SqlClient;
using System.Collections.ObjectModel;
using System.Data.Common;

namespace CH.Study.ConsoleApp.ExpressionTree
{
    public class MsSqlQueryExpressionTranslator : QueryExpressionTranslator
    {
      
        public MsSqlQueryExpressionTranslator()
        {
          
        }



        public override string Translate(Expression expression)
        {
            base.sb = new StringBuilder();
            base.parameter = new List<DbParameter>();
            this.expression = expression;
            this.Visit(expression);
            return sb.ToString();
        }
     
        protected override Expression VisitConstant(ConstantExpression c)
        {
            IQueryable q = c.Value as IQueryable;

            if (q != null)
            {
                sb.Append(q.ElementType.Name);
            }
            else
            {
                //生成参数 @p1
                string paramName = "@p" + index;
                //设置下一个参数计数器
                index += 1;
                //设置参数
                base.parameter.Add(new SqlParameter(paramName, c.Value));
                sb.Append(paramName);
            }
            return c;
        }

     


    }
}
